package com.v1.video.fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.iss.view.common.ToastAlone;
import com.iss.view.pulltorefresh.PullToRefreshBase;
import com.iss.view.pulltorefresh.PullToRefreshBase.Mode;
import com.iss.view.pulltorefresh.PullToRefreshBase.OnRefreshListener2;
import com.iss.view.pulltorefresh.PullToRefreshGridView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.activity.OtherPersonHomeActivity;
import com.v1.video.activity.PaikeVideoDetailActivity2;
import com.v1.video.domain.LoginInfo;
import com.v1.video.domain.ScenarioVideoInfo;
import com.v1.video.domain.TopicListInfoConfig;
import com.v1.video.domain.VideoInfo;
import com.v1.video.engine.NetEngine;
import com.v1.video.util.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * 普通话题碎片
 * 
 * @author wangfang
 * 
 */
public class CommonTopicFragment extends V1BaseFragment {

	private View mView;
	private String mActionID;
	private String mActionName;
	private GridView mGridView;
	private PullToRefreshGridView mRefreshGridView;
	private CommonTopicAdapter mAdapter;
	private int mPageIndex = 1;
	private ProgressDialog pd;

	public String getmActionID() {
		return mActionID;
	}

	public void setmActionID(String mActionID) {
		this.mActionID = mActionID;
	}

	public String getmActionName() {
		return mActionName;
	}

	public void setmActionName(String mActionName) {
		this.mActionName = mActionName;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		mView = inflater.inflate(R.layout.fragment_commontop, container, false);
		initView();
		initData();
		setListener();
		return mView;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (pd != null) {
			if (pd.isShowing()) {
				pd.dismiss();
			}
			pd = null;
		}
		if (mAdapter != null) {
			mAdapter = null;
		}
	}

	private void initView() {
		mRefreshGridView = (PullToRefreshGridView) mView
				.findViewById(R.id.gv_gridView);
		mRefreshGridView.setScrollingWhileRefreshingEnabled(false);
		mRefreshGridView.setMode(Mode.BOTH);
		mGridView = mRefreshGridView.getRefreshableView();
	}

	private void initData() {
		mAdapter = new CommonTopicAdapter(getActivity());
		mGridView.setAdapter(mAdapter);
		loadData();
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void setListener() {
		mRefreshGridView.setOnRefreshListener(new OnRefreshListener2() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase refreshView) {
				// TODO Auto-generated method stub
				mPageIndex = 1;
				loadData();
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase refreshView) {
				// TODO Auto-generated method stub
				loadData();
			}
		});

		mGridView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				switch (scrollState) {
				case OnScrollListener.SCROLL_STATE_IDLE:
					ImageLoader.getInstance().resume();
					break;
				case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
					ImageLoader.getInstance().pause();
					break;
				case OnScrollListener.SCROLL_STATE_FLING:
					ImageLoader.getInstance().pause();
					break;
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub

			}
		});
	}

	/**
	 * 加载数据
	 */
	private void loadData() {
		if (!TextUtils.isEmpty(mActionID) || !TextUtils.isEmpty(mActionName)) {
			new CommonTopicAsyncTask(mActionID, mActionName).execute();
		}
	}

	/**
	 * 重置数据
	 */
	private void resetDate() {
		if (mPageIndex == 1 && mAdapter != null
				&& mAdapter.getmLstData() != null
				&& mAdapter.getmLstData().size() > 0) {
			mAdapter.getmLstData().clear();
			mAdapter.notifyDataSetChanged();
		}
	}

	/**
	 * 
	 * @author wangfang
	 * 
	 */
	public class CommonTopicAdapter extends BaseAdapter {

		private final String TAG = "CommonTopicAdapter";
		private Context mContext;
		private LayoutInflater mLayoutInflater;
		private List<VideoInfo> mLstData;
		private int mHeight;

		public CommonTopicAdapter(Context context) {
			this.mContext = context;
			mLayoutInflater = LayoutInflater.from(mContext);
			mLstData = new ArrayList<VideoInfo>();
			mHeight = Utils.computeImageHeight(context, 21);
		}

		public List<VideoInfo> getmLstData() {
			return mLstData;
		}

		public void setmLstData(List<VideoInfo> mLstData) {
			this.mLstData.addAll(mLstData);
			this.notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mLstData.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return mLstData.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			Holder holder = null;
			if (convertView == null) {
				convertView = mLayoutInflater.inflate(
						R.layout.grid_waterfall_item, null);
				holder = new Holder();
				holder.layItem = (LinearLayout) convertView
						.findViewById(R.id.lay_item);
				holder.image = (ImageView) convertView
						.findViewById(R.id.iv_image);
				holder.title = (TextView) convertView
						.findViewById(R.id.tv_title);
				holder.subtitle = (TextView) convertView
						.findViewById(R.id.tv_subtitle);
				convertView.setTag(holder);
			} else {
				holder = (Holder) convertView.getTag();
			}
			final VideoInfo info = mLstData.get(position);
			if (!TextUtils.isEmpty(info.getRecommendTitle())) {
				holder.title.setText(info.getRecommendTitle());
			} else if (!TextUtils.isEmpty(info.getTitle())) {
				holder.title.setText(info.getTitle());
			} else {
				holder.title.setText("");
			}
			if (!TextUtils.isEmpty(info.getRecommendDetail())) {
				holder.subtitle.setText(info.getRecommendDetail());
			} else if (info.getUserInfo() != null
					&& (!TextUtils.isEmpty(info.getUserInfo().getNickname()) || !TextUtils
							.isEmpty(info.getUserInfo().getUserName()))) {
				if (!TextUtils.isEmpty(info.getUserInfo().getNickname())) {
					holder.subtitle.setText(info.getUserInfo().getNickname());
				} else if (!TextUtils.isEmpty(info.getUserInfo().getUserName())) {
					holder.subtitle.setText(info.getUserInfo().getUserName());
				}
				holder.subtitle.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (info != null
								&& info.getUserInfo() != null
								&& !TextUtils.isEmpty(info.getUserInfo()
										.getUserId())) {
							String userId = info.getUserInfo().getUserId();
							Intent intent = new Intent();
							if (LoginInfo.getInstance().isLogin()) {
								if (!TextUtils.isEmpty(userId)
										&& userId.equals(LoginInfo
												.getInstance().getUserId())) {
//									intent.setClass(mContext,
//											PersonalHomeActivity.class);
//									mContext.startActivity(intent);
								} else {
									intent.setClass(mContext,
											OtherPersonHomeActivity.class);
									intent.putExtra("userId", userId);
									mContext.startActivity(intent);
								}
							} else {
								intent.setClass(mContext,
										OtherPersonHomeActivity.class);
								intent.putExtra("userId", userId);
								mContext.startActivity(intent);
							}
						}
					}
				});
			} else {
				holder.subtitle.setText("");
			}
			android.view.ViewGroup.LayoutParams Params = holder.image
					.getLayoutParams();
			Params.width = LayoutParams.MATCH_PARENT; // 设置图片的宽度
			Params.height = mHeight;// 设置图片的高度
			holder.image.setLayoutParams(Params);
			holder.layItem.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (info != null && !TextUtils.isEmpty(info.getVideoId())) {
						ScenarioVideoInfo video = new ScenarioVideoInfo(info
								.getVideoId());
						if (video != null) {
							Intent intent = new Intent();
							intent.setClass(getActivity(),
									PaikeVideoDetailActivity2.class);
							intent.putExtra("videoInfo", video);
							startActivity(intent);
						}
					}
				}
			});
			if (!TextUtils.isEmpty(info.getRecommendImageUrl())) {
				ImageLoader.getInstance().displayImage(
						info.getRecommendImageUrl(), holder.image,
						Constant.VIDEO_9_16_OPTION, null);
			} else if (!TextUtils.isEmpty(info.getImgUrl())) {
				ImageLoader.getInstance().displayImage(info.getImgUrl(),
						holder.image, Constant.VIDEO_9_16_OPTION, null);
			} else {
				holder.image.setImageResource(R.drawable.common_place_holder_bg);
			}
			return convertView;
		}

		private class Holder {
			public LinearLayout layItem;
			public ImageView image;
			public TextView title;
			public TextView subtitle;
		}
	}

	private class CommonTopicAsyncTask extends
			AsyncTask<Void, Void, TopicListInfoConfig> {

		private String errorMsg = "";
		private String categoryId;
		private String categoryName;

		public CommonTopicAsyncTask(String categoryId, String categoryName) {
			this.categoryId = categoryId;
			this.categoryName = categoryName;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			pd = Utils.getProgressDialog(getActivity(), this);
			pd.show();
		}

		@Override
		protected TopicListInfoConfig doInBackground(Void... params) {
			// TODO Auto-generated method stub

			try {
				return new NetEngine().queryTopicVideoList(categoryId,
						categoryName, "latest", mPageIndex + "",
						Constant.WATERFULL_PAGE_SIZE + "");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				errorMsg = e.getMessage();
			}
			return null;
		}

		@Override
		protected void onPostExecute(TopicListInfoConfig result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (pd != null && pd.isShowing()) {
				pd.cancel();
			}
			pd = null;
			if (mRefreshGridView != null) {
				mRefreshGridView.onRefreshComplete();
			}
			resetDate();
			if (!TextUtils.isEmpty(errorMsg)) {
				ToastAlone.showToast(getActivity(), errorMsg, 1);
			} else {
				if (result != null && mRefreshGridView != null
						&& mAdapter != null && result.getObj() != null
						&& result.getObj().getVideos() != null
						&& result.getObj().getVideos().size() > 0) {
					int numLeight = mPageIndex * Constant.WATERFULL_PAGE_SIZE;
					if (numLeight < result.getObj().getTotal()) {
						mAdapter.setmLstData(result.getObj().getVideos());
						mRefreshGridView.setMode(Mode.BOTH);
					} else {
						mAdapter.setmLstData(result.getObj().getVideos());
						mRefreshGridView.setMode(Mode.PULL_FROM_START);
					}
					mPageIndex++;
				}
			}
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
			if (mRefreshGridView != null) {
				mRefreshGridView.onRefreshComplete();
			}
		}
	}
}
